<template>
    <div class="api-content">
        <div class="api-content-box">
            <div class="titleBox">
                <el-select v-model="contentValue.newValue.status" @input="checkChangeValue" class="api-state-change" :class="stateNumArray[contentValue.newValue.status]" placeholder="请选择" :popper-class="theme + ' api-state-change-option'">
                    <el-option v-for="item in stateArray" :class="stateNumArray[item.value]" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
                <div class="api-title-box">
                    <input class="title" ref="titleEle" type="text" placeholder="请输入标题" @input="checkChangeValue" v-model="contentValue.newValue.title" @focus="contentValue.newValue.title == 'new File' ? contentValue.newValue.title = '' : '' " @blur="titleBlur">
                </div>
            </div>
            <div class="textarea-box">
                <el-input type="textarea" resize="none" @input="checkChangeValue" :autosize="{ minRows: 3, maxRows: 3}" show-word-limit maxlength="200" placeholder="备注" v-model="contentValue.newValue.description">
                </el-input>
            </div>
            <div class="main-line">
                <el-input placeholder="输入访问地址" @input="checkChangeValue" v-model="contentValue.newValue.url" class="input-with-select">
                    <div slot="prepend">
                        <el-dropdown @command="changeSelect" class="content-type" trigger="click">
                            <el-button>
                                <span class="type" :class="typeClass[contentValue.newValue.type]">
                                    {{contentValue.newValue.type}}
                                </span>
                            </el-button>
                            <el-dropdown-menu slot="dropdown" :class="theme">
                                <el-dropdown-item command="GET"><span class="type text_green">GET</span>
                                </el-dropdown-item>
                                <el-dropdown-item command="POST"><span class="type text_orange">POST</span>
                                </el-dropdown-item>
                                <el-dropdown-item command="PUT"><span class="type text_blue">PUT</span>
                                </el-dropdown-item>
                                <el-dropdown-item command="DEL"><span class="type text_red">DEL</span>
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                        &nbsp; &nbsp; &nbsp; &nbsp;
                        <el-dropdown class="ipBox" @command="IPSelect" placement="bottom-start" trigger="click">
                            <el-button>
                                <span class="ip">{{IP ? IP : '请选择地址'}}</span>
                            </el-button>
                            <el-dropdown-menu slot="dropdown" :class="theme">
                                <el-dropdown-item v-for="(item, index) in urlArray" :key="index" :command="index">
                                    <span class="ip">
                                        {{item.title + ' : ' + item.type + item.str + (item.port == 80 ? '' : ':' + item.port)}}
                                    </span>
                                </el-dropdown-item>
                                <el-dropdown-item command="clear" v-if="IP"><span class="ip">清空</span>
                                </el-dropdown-item>
                                <el-dropdown-item command="setting"><span class="ip">管理IP地址</span>
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </div>
                    <div class="sendButton" slot="append" @click="send">
                        <span>{{showCancelSend ? 'Cancel' : 'Send'}}</span>
                        <el-dropdown class="otherOption" @command="optionSelect" trigger="click" style="color: #FFF">
                            <el-button @click.stop>
                                <i class=" el-icon-arrow-down el-icon--right"></i>
                            </el-button>
                            <el-dropdown-menu slot="dropdown" :class="theme">
                                <el-dropdown-item command="Save"><span class="text_green">保存</span>
                                </el-dropdown-item>
                                <el-dropdown-item command="Restore"><span class="text_orange">还原</span>
                                </el-dropdown-item>
                                <el-dropdown-item command="Delete"><span class="text_red">删除</span>
                                </el-dropdown-item>
                                <el-dropdown-item command="SaveAs"><span class="text_blue">另存为</span>
                                </el-dropdown-item>
                                <el-dropdown-item command="export"><span class="text_blue">导出 ShowDoc 文档</span>
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </div>
                </el-input>
            </div>
            <reqBox ref="headerBox" :newValue="contentValue.newValue" :checkChangeValue="checkChangeValue">
            </reqBox>
            <div class="ResponseBox">
                <div class="Response-title">
                    <span>Response</span>
                    <div class="resOptions">
                        Status:{{resOptions.Status}} &nbsp; Time:{{resOptions.Time}} ms &nbsp; Size:{{resOptions.Size}}
                    </div>
                </div>
                <div class="Response-content">
                    <div class="bodyType">
                        &nbsp;&nbsp;&nbsp;
                        <el-radio-group v-model="ResponseType">
                            <el-radio :label="1">返回值</el-radio>
                            <el-radio :label="2">请求头</el-radio>
                        </el-radio-group>
                        <el-button size="mini" style="float:right" @click="responseBox = true">返回值模型</el-button>
                    </div>
                    <div class="Response-headers" :style="{'display' : ResponseType == 1 ? 'none' : 'block'}">
                        <repHeader ref="ResponseHeaders"></repHeader>
                    </div>
                    <el-button v-if="isFile" size="mini" class="ContentToFile" type="info" @click="imagePorviewEvent">以文件形式预览</el-button>
                    <transition name="el-fade-in">
                        <div class="cancel-mark" v-if="showCancelSend">
                            <el-button type="info" @click="cancelSend">取消发送</el-button>
                        </div>
                    </transition>
                    <textarea ref="Response"></textarea>
                </div>
            </div>
            <el-drawer title="编辑返回值模型" :wrapperClosable="false" :direction="'rtl'" append-to-body destroy-on-close size="850px" :visible.sync="responseBox">
                <response :newValue="contentValue.newValue" :checkChangeValue="checkChangeValue"></response>
            </el-drawer>
            <el-dialog :title="'导出 ShowDoc 文档'" :close-on-click-modal="false" append-to-body :visible.sync="showExportShowDoc" width="800px">
                <exportShowDoc ref="ShowDocEle"></exportShowDoc>
            </el-dialog>

            <el-dialog :title="'图片预览'" :close-on-click-modal="false" append-to-body :visible.sync="showImagePorView" width="800px">
                <imagePorview ref="imagePorview"></imagePorview>
            </el-dialog>

        </div>
    </div>
</template>
<script>
let CodeMirror = require("codemirror/lib/codemirror");
import "codemirror/lib/codemirror.css";
import "codemirror/theme/mdn-like.css";
import "codemirror/mode/javascript/javascript.js";
import "codemirror/addon/fold/foldgutter.css";
import "codemirror/addon/fold/foldcode.js";
import "codemirror/addon/fold/foldgutter.js";
import "codemirror/addon/fold/brace-fold.js";
import "codemirror/addon/fold/comment-fold.js";
import "codemirror/addon/edit/matchbrackets";
import 'codemirror/addon/hint/javascript-hint'
import 'codemirror/addon/hint/show-hint'
import 'codemirror/keymap/sublime.js'
import 'codemirror/keymap/emacs.js'
import 'codemirror/keymap/vim.js'


import reqBox from './reqBox';
import { mapState } from 'vuex';

import response from '../custom/response'
import exportShowDoc from './exportShowDoc'
import repHeader from './ResponseHeaders'

import commonEvent from '../../../../assets/commonEvent'
import imagePorview from '../../other/imagePorview'

export default {
    components: {
        reqBox,
        exportShowDoc,
        repHeader,
        response,
        imagePorview,
    },
    computed: {
        ...mapState("Tree", {
            folderObject: state => state.folderObject,
        }),
        ...mapState("url", {
            urlArray: state => state.urlArray,
            activeUrl: state => state.activeUrl,
        }),
        ...mapState("theme", {
            theme: state => state.theme,
        }),
        ...mapState("model", {
            models: state => state.models,
        }),
    },
    watch: {
        activeUrl(newValue, oldValue) {
            if (newValue) {
                this.IP = newValue.type + newValue.str + (newValue.port == 80 ? '' : ':' + newValue.port)
            } else {
                this.IP = ''
            };
        },
    },
    props: ['contentValue', 'removeTag'],
    mounted() {
        this.Response = CodeMirror.fromTextArea(this.$refs.Response, {
            mode: 'text/javascript',
            indentWithTabs: true,
            smartIndent: false,
            lineNumbers: true,
            lineWrapping: true,
            foldGutter: true,
            readOnly: true,
            matchBrackets: true,
            gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
            theme: 'mdn-like',
        });
        if (this.activeUrl) {
            this.IP = this.activeUrl.type + this.activeUrl.str + (this.activeUrl.port == 80 ? '' : ':' + this.activeUrl.port)
        };
    },
    data() {
        return {
            showImagePorView: false,
            isFile: false,
            responseBox: false,
            ResponseType: 1,
            showExportShowDoc: false,
            reqEvent: null,
            ResponseMessage: '',
            showCancelSend: false,
            Response: null,
            resOptions: {
                Status: '--',
                Time: '--',
                Size: '--'
            },
            IP: '',
            lastResponse: '',
            showHeader: false,
            stateNumArray: {
                0: 'text_orange',
                1: 'text_blue',
                2: 'text_red',
                3: 'text_green',
                4: 'text_gray',
                undefined: 'text_transparent',
                null: 'text_transparent',
            },
            typeClass: {
                GET: 'text_green',
                POST: 'text_orange',
                PUT: 'text_blue',
                DEL: 'text_red'
            },
            stateArray: [
                { value: 0, label: '设计中' },
                { value: 1, label: '进行中' },
                { value: 2, label: '异常' },
                { value: 3, label: '已完成' },
                { value: 4, label: '已废弃' }
            ],
        }
    },
    methods: {
        checkChangeValue() {
            if (this.contentValue.id) {
                var checkArray = ['title', 'status', 'bodyType', 'description', 'type', 'url', 'header', 'body', 'fromdata', 'query', 'rest', 'before', 'after', 'response'];
                var isChange = false;
                for (let i = 0; i < checkArray.length; i++) {
                    const element = checkArray[i];
                    if (this.contentValue.newValue[element] != this.contentValue.oldValue[element]) {
                        isChange = true;
                        break;
                    };
                };
                this.contentValue.isChange = isChange;
            } else {
                this.contentValue.isChange = true;
            };
        },
        titleBlur() {
            this.contentValue.newValue.title == '' ? this.contentValue.newValue.title = 'new File' : '';
            this.checkChangeValue();
        },
        IPSelect(str) {
            if (str == 'clear') {
                this.$store.dispatch('url/setActiveUrl', null);
            } else if (str == 'setting') {
                this.$store.dispatch('customKey/showCustomDrawer', {
                    activeObj: null,
                    type: 'url'
                });
            } else {
                this.$store.dispatch('url/setActiveUrl', this.urlArray[str]);
            };
        },
        changeSelect(type) {
            this.contentValue.newValue.type = type;
            this.checkChangeValue();
        },
        send() {
            if (!this.showCancelSend) {
                this.showCancelSend = true;
                this.requestOpenCheck((res) => {
                    if (res) {
                        this.showCancelSend = true;
                        this.requestEvent(res);
                    } else {
                        this.showCancelSend = false;
                    }
                });
            } else {
                this.reqEvent.abort();
                this.showCancelSend = false;
            };
        },
        cancelSend() {
            this.showCancelSend = false;
        },
        optionSelect(str) {
            if (str == 'Restore') {
                this.$refs.headerBox.closeChange();
                var checkArray = ['title', 'status', 'description', 'type', 'url', 'header', 'body', 'fromdata', 'query', 'rest', 'before', 'after', 'response'];
                for (let i = 0; i < checkArray.length; i++) {
                    const element = checkArray[i];
                    this.contentValue.newValue[element] = this.contentValue.oldValue[element];
                };
                setTimeout(() => {
                    this.$refs.headerBox.restore();
                }, 100);
                this.checkChangeValue();
            } else if (str == 'Delete') {
                var confirm = this.$confirm('是否删除接口？');
                if (confirm) {
                    this.$store.dispatch('Tree/deleteApi', {
                        id: this.contentValue.oldValue.id,
                        callback: () => {
                            this.removeTag(this.contentValue.UUID);
                        }
                    });
                };
            } else if (str == 'SaveAs') {
                this.$store.dispatch('Tree/getTree', folderList => {
                    this.$store.dispatch('saveFolder/setFolderObject', {
                        folderList: folderList,
                        apiObject: this,
                        type: 'saveAsEvent'
                    });
                    this.$store.dispatch('saveFolder/changeFolderStatus', true);
                })
            } else if (str == 'Save') {
                this.$refs.titleEle.blur();
                // this.titleBlur();
                if (this.contentValue.id) {
                    this.saveEvent();
                } else {
                    this.$store.dispatch('Tree/getTree', folderList => {
                        this.$store.dispatch('saveFolder/setFolderObject', {
                            folderList: folderList,
                            apiObject: this,
                            type: 'saveEvent'
                        });
                        this.$store.dispatch('saveFolder/changeFolderStatus', true);
                    })
                };
            } else if (str == 'export') {
                // console.log('导出');
                this.showExportShowDoc = true;
                // addData

                this.$nextTick(() => {
                    this.$refs['ShowDocEle'].addData(this.contentValue.newValue, this.lastResponse);
                });


            };
        },
        afterSave(apiId) {
            if (apiId) {
                this.contentValue.id = apiId;
            };
            var checkArray = ['title', 'status', 'description', 'type', 'url', 'header', 'body', 'fromdata', 'query', 'rest', 'before', 'after', 'response'];
            for (let i = 0; i < checkArray.length; i++) {
                const element = checkArray[i];
                if (element == 'response') {
                    this.contentValue.oldValue[element] = JSON.parse(JSON.stringify(this.contentValue.newValue[element]));
                } else {
                    this.contentValue.oldValue[element] = this.contentValue.newValue[element];
                }
            };
            if (apiId) {
                this.contentValue.oldValue.id = apiId;
            };
            this.contentValue.isChange = false;
            if (apiId) {
                this.$store.dispatch('ApiActive/setActiveId', apiId)
            };
        },
        saveEvent(folderId) {
            if (!folderId && this.contentValue.isChange) {
                var confirm = this.$confirm('是否更新服务器数据？');
                if (confirm) {
                    this.$store.dispatch('Tree/updataApi', {
                        id: this.contentValue.oldValue.id,
                        apiData: this.contentValue.newValue,
                        callback: (res) => {
                            this.afterSave();
                        }
                    });
                };
            } else if (folderId && this.contentValue.isChange) {
                var confirm = this.$confirm('是否更新服务器数据？');
                if (confirm) {
                    this.$store.dispatch('Tree/creatApi', {
                        apiData: this.contentValue.newValue,
                        folderId: folderId,
                        callback: (res) => {
                            this.afterSave(res);
                        }
                    });
                };
            };
        },
        saveAsEvent(folderId) {
            var confirm = this.$confirm('是否更新服务器数据？');
            if (confirm) {
                this.$store.dispatch('Tree/creatApi', {
                    apiData: this.contentValue.newValue,
                    folderId: folderId,
                    callback: (res) => {
                        this.$nextTick(() => {
                            this.$store.dispatch('ApiActive/setActiveId', res)
                        });
                    }
                });
            };
        },
        requestOpenCheck(callback) {
            this.ResponseMessage = '';
            commonEvent.checkRequestlegal(this.contentValue.newValue, this.IP, (error, data) => {
                if (error) {
                    this.$alert(error);
                    callback(false);
                } else {
                    callback(data);
                }
            });
        },
        imagePorviewEvent() {
            this.showImagePorView = true;
            this.$nextTick(() => {
                var ContentType = this.lastResponseData.response.headers['content-type'].toLocaleLowerCase();
                var Content = this.lastResponse;
                this.$refs.imagePorview.setData('reqEvent', ContentType, Content);
            });

        },
        requestEvent(res) {
            var _res = res
            this.Response.setValue('');
            this.resOptions.Time = '--';
            this.resOptions.Size = '--';
            this.resOptions.Status = '--';
            this.isFile = false;
            this.reqEvent = commonEvent.requestEvent(_res, JSON.parse(this.contentValue.newValue.response), (resEventData) => {
                // console.log(resEventData);
                this.$refs.ResponseHeaders.setData(this.reqEvent, res.body, res.query, resEventData.response);
                var ContentType = resEventData.response.headers['content-type'].toLocaleLowerCase();
                if (ContentType == 'image/png' || ContentType == 'image/jpeg' || ContentType == 'image/gif') {
                    this.isFile = true;
                };
                if (resEventData.error) {
                    this.Response.setValue(resEventData.error.toString());
                    if (resEventData.error.code) {
                        this.resOptions.Status = resEventData.error.code;
                    } else {
                        this.resOptions.Status = '--';
                    };
                    this.resOptions.Time = '--';
                    this.resOptions.Size = '--';
                    this.showCancelSend = false;
                } else {
                    this.showCancelSend = false;
                    var bodySize = 0;
                    if (resEventData.body && resEventData.body.length > 1024) {
                        bodySize = resEventData.body.length / 1024;
                        bodySize = bodySize.toFixed(2) + 'KB';
                    } else if (resEventData.body) {
                        bodySize = resEventData.body.length + 'B';
                    };
                    this.resOptions.Size = bodySize;
                    this.resOptions.Status = resEventData.response.statusCode + ' ' + resEventData.response.statusMessage;
                    this.resOptions.Time = resEventData.response.elapsedTime;

                    this.Response.setValue(resEventData.output);
                    this.lastResponse = resEventData.output;
                    this.lastResponseData = resEventData;
                };
            });
            // console.log(this.reqEvent);
            this.$refs.ResponseHeaders.setData(this.reqEvent, res.body, res.query);
        }
    },
}

</script>